package com.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.entity.ChongdianzhuangEntity;
import com.entity.ChongdianzhuangOrderEntity;
import com.service.ChongdianzhuangOrderService;
import com.service.ChongdianzhuangService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Configuration
@EnableScheduling
public class MinuteTask {
    @Autowired
    private ChongdianzhuangOrderService chongdianzhuangOrderService;
    @Autowired
    private ChongdianzhuangService chongdianzhuangService;

    // 实现定时任务的具体逻辑
    @Transactional
    @Scheduled(cron = "0 * * * * ?") // 每分钟执行一次
    public void executeTask() {
        System.out.println("定时任务执行时间：" + LocalDateTime.now());
        List<ChongdianzhuangOrderEntity> chongdianzhuangOrderEntities = chongdianzhuangOrderService.selectList(null)
                .stream().filter(entity -> !entity.getIsstop()).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(chongdianzhuangOrderEntities)) return;
        List<ChongdianzhuangEntity> chongdianzhuangEntities = chongdianzhuangService.selectList(null);
        Map<String, ChongdianzhuangEntity> chongdianzhuangEntityMap = chongdianzhuangEntities.stream()
                .collect(Collectors.toMap(ChongdianzhuangEntity::getDianzhuangbianhao, Function.identity()));
        for (ChongdianzhuangOrderEntity chongdianzhuangOrderEntity : chongdianzhuangOrderEntities) {
            // 获取当前中国时区时间
            ZoneId chinaZone = ZoneId.of("Asia/Shanghai");
            LocalDateTime currentLocalTime = LocalDateTime.now(chinaZone);
            // 指定时间加上所需分钟数
            LocalDateTime futureTime = chongdianzhuangOrderEntity.getStarttime().plusMinutes(chongdianzhuangOrderEntity.getTime());
            // 判断当前时间是否大于等于未来时间
            boolean isCurrentTimeGreaterOrEqual = currentLocalTime.compareTo(futureTime) >= 0;
            if (isCurrentTimeGreaterOrEqual) {
                // 停止充电
                chongdianzhuangOrderEntity.setIsstop(Boolean.TRUE);
                chongdianzhuangOrderService.updateById(chongdianzhuangOrderEntity);
                ChongdianzhuangEntity chongdianzhuang = chongdianzhuangEntityMap.get(chongdianzhuangOrderEntity.getDianzhuangbianhao());
                chongdianzhuang.setStatus("空闲中");
                chongdianzhuangService.updateById(chongdianzhuang);
            }
        }
    }
}
